'use strict';
const dayjs = require("dayjs");

module.exports = app => {
    const { INTEGER, STRING, DATE, DECIMAL } = app.Sequelize;
    const OrderItem = app.model.define(
        'OrderItem',
        {
            id: { type: INTEGER, primaryKey: true, autoIncrement: true },
            order_id: { type: INTEGER, allowNull: false, comment: '订单ID' },
            item_id: { type: INTEGER, allowNull: false, comment: '物品ID' },
            item_name: { type: STRING(100), allowNull: false, comment: '物品名称' },
            quantity: { type: INTEGER, allowNull: false, defaultValue: 1, comment: '数量' },
            weight: { type: DECIMAL(10, 2), allowNull: true, comment: '重量（kg）' },
            volume: { type: DECIMAL(10, 2), allowNull: true, comment: '体积（立方米）' },
            price: { type: DECIMAL(10, 2), allowNull: true, comment: '价格' },
            subtotal: { type: DECIMAL(10, 2), allowNull: true, comment: '小计' },
            create_time: {
                type: DATE,
                get() {
                    return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            update_time: {
                type: DATE,
                get() {
                    return dayjs(this.getDataValue('update_time')).format('YYYY-MM-DD HH:mm:ss');
                }
            }
        },
        {
            tableName: 'order_item',
            timestamps: true,
            createdAt: 'create_time',
            updatedAt: 'update_time'
        }
    );

    OrderItem.associate = function() {
        app.model.OrderItem.belongsTo(app.model.ExpressOrder, { foreignKey: 'order_id', targetKey: 'id', as: 'order' });
        app.model.OrderItem.belongsTo(app.model.Item, { foreignKey: 'item_id', targetKey: 'id', as: 'item' });
    };

    return OrderItem;
};
